<script setup lang="jsx">
import { reactive, ref } from 'vue';
import { UUID } from 'uuidjs';
import { parseTime } from '@/utils';
import { erpsyncmespubtechnology, pubtechnologySelect } from '@/service/api/modules/erp';
import Modal from '@/components/common/modal.vue';
import Form from '@/components/common/form.vue';
// 增删改查
import {
  addTechnologyProcess, // 新增
  deleteTechnologyProcess, // 删除
  editTechnologyProcess // 修改
  // exportTechnologyProcess // 导出
} from '@/service/api/modules/engineering';

import Search from './modules/search.vue';
import Add from './modules/add.vue';
const searchParams = ref({
  techName: '', // 工艺名称
  techNo: '' // 工艺编码
});

const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: total => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current, size) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});

// 页面表格展示数据
const columns = ref([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 100,
    align: 'center',
    checked: true
  },
  {
    key: 'techName',
    dataIndex: 'techName',
    title: '工艺名称',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'techNo',
    dataIndex: 'techNo',
    title: '工艺编码',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'techType',
    dataIndex: 'techType',
    title: '工艺类型',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.techType == 0) {
        return '一般工艺';
      }
      if (record.techType == 1) {
        return '成型工艺';
      }
      if (record.techType == 2) {
        return '压合工艺';
      }
      if (record.techType == 3) {
        return '包装工艺';
      }
      if (record.techType == 5) {
        return '钻孔工艺';
      }
      if (record.techType == 6) {
        return '阻抗测试工艺';
      }
      if (record.techType == 10) {
        return '空';
      }
    }
  },
  {
    key: 'passOver',
    dataIndex: 'passOver',
    title: '是否过数',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.passOver == 0) {
        return '否';
      }
      if (record.passOver == 1) {
        return '是';
      }
    }
  },
  {
    key: 'workUnit',
    dataIndex: 'workUnit',
    title: '出账单位',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '创建时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.createDate == null) {
        return null;
      }
      return parseTime(record.createDate);
    }
  },
  {
    key: 'updateDate',
    dataIndex: 'updateDate',
    title: '修改时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.updateDate == null) {
        return null;
      }
      return parseTime(record.updateDate);
    }
  },
  {
    key: 'lmTime',
    dataIndex: 'lmTime',
    title: '同步时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.lmTime == null) {
        return null;
      }
      return parseTime(record.lmTime);
    }
  }
]);
const crDatas = ref({});
const detailsVisibleQrcode = ref(false);
// 同步弹窗表单
const formListqr = [
  {
    type: 'input',
    key: 'techName',
    label: '工艺名称',
    placeholder: '请输入工艺名称',
    span: 24
  }
];
const tableData = ref([]);
const loading = ref(false);
const defaultExpandedRowKeys = ref([]);
const selectedRowKeys = ref([]);
function tableSelectChange(val) {
  selectedRowKeys.value = val;
  // 打印当前行数据
  console.log(val);
}
function tableSelectChanges() {
  selectedRowKeys.value = [];
}
const addFormRef = ref(null);
const modalVisible = ref(false);

// 表格数据展示
function getData() {
  loading.value = true;
  pubtechnologySelect({
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    ...searchParams.value
  })
    .then(({ data, error }) => {
      if (!error) {
        data.list.forEach((item, index) => {
          item.index = index + 1;
          // item.techID = UUID.genV4().hexNoDelim;
        });
        tableData.value = data.list;
        pagination.total = data.total;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

const currentRow = ref(null);
const formTit = ref('');

const operateType = ref('add');
// 新增弹窗
function manualSyncing() {
  currentRow.value = null; // 清空当前行数据
  modalVisible.value = true;
  formTit.value = '工艺流程信息新增';
  operateType.value = 'add';
}

// 新增和修改表单提交按钮
async function boundUpdataAdd(val) {
  const form = { ...addFormRef.value };
  await form.validateForm();
  const formDataA = form.model;

  if (val === '工艺流程信息新增') {
    addTechnologyProcess(formDataA).then(({ data, error }) => {
      if (!error) {
        window.$message?.success('新增成功');
        modalVisible.value = false;
        getData();
      }
    });
  } else {
    editTechnologyProcess({ techID: selectedRowKeys.value[0], ...formDataA }).then(({ data, error }) => {
      if (!error) {
        window.$message?.success('修改成功');
        selectedRowKeys.value = [];
        currentRow.value = null;
        modalVisible.value = false; // 关闭弹窗
        getData();
      }
    });
  }
  // 清空新增表单
  model.value.deliverytarget = '';
  console.log(formDataA);
}
// 修改表单
function updateSyncing() {
  if (selectedRowKeys.value.length !== 1) {
    return window.$message?.error('请选择一条数据');
  }

  // 获取要编辑的行数据
  const selectedRow = tableData.value.find(row => row.techID === selectedRowKeys.value[0]);
  console.log('selectedRow', selectedRow);

  if (selectedRow) {
    currentRow.value = selectedRow; // 将行数据赋值给 currentRow
    formTit.value = '工艺流程信息修改';
    modalVisible.value = true;
    operateType.value = 'edit';
  }
}
// 删除表单
// 删除表单
function deleteSyncing() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请选择数据');
  }
  window.$modal.confirm({
    title: '提醒',
    content: '确认删除所选数据吗？',
    onOk: () => {
      const deletePromises = selectedRowKeys.value.map(key => {
        return deleteTechnologyProcess({ techID: key }); // 使用单个 techID 进行删除
      });

      Promise.all(deletePromises).then(results => {
        const errors = results.filter(result => result.error);
        if (errors.length > 0) {
          window.$message?.error('删除失败');
        } else {
          window.$message?.success('删除成功');
          selectedRowKeys.value = [];
          getData();
        }
      });
    },
    onCancel: () => {}
  });
}

getData();

getData();

// 同步弹窗
function Syncing() {
  crDatas.value = {};
  detailsVisibleQrcode.value = true;
}
// 手动同步
function boundUpdata() {
  erpsyncmespubtechnology(crDatas.value).then(({ data, error }) => {
    if (!error) {
      window.$message?.success('手动同步成功');
      detailsVisibleQrcode.value = false;
      getData();
    }
  });
}
getData();

// 导出
// function exportExcel() {
//   exportTechnologyProcess({ ...searchParams.value });
// }

function search() {
  pagination.current = 1;
  getData();
}

const currentRowId = ref(null);
const customRow = record => {
  return {
    style: {
      background: record.techID === currentRowId.value ? '#BAEAFA' : ''
    },
    class: record.techID === currentRowId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      currentRowId.value = record.techID;
    }
  };
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search
      v-model:model="searchParams"
      :selected-row-keys="selectedRowKeys"
      @reset="search()"
      @search="search()"
      @reset-checked="tableSelectChanges"
    />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="Syncing">
          <span class="ml-3px">手动同步</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="manualSyncing">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">新增</span>
        </AButton>
        <!-- 修改 -->
        <AButton
          type="primary"
          size="small"
          ghost
          class="mini-btn mr-8px"
          :disabled="selectedRowKeys.length !== 1"
          @click="updateSyncing"
        >
          <template #icon>
            <icon-ic-round-edit class="align-sub text-icon" />
          </template>
          <span class="ml-3px">修改</span>
        </AButton>
        <!-- 删除 -->
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="deleteSyncing">
          <template #icon>
            <icon-ic-round-delete class="align-sub text-icon" />
          </template>
          <span class="ml-3px">删除</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <!-- 页面表格 -->
      <STable
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: tableSelectChange }"
        :default-expanded-row-keys="defaultExpandedRowKeys"
        :columns="columns"
        :data-source="tableData"
        size="small"
        bordered
        :loading="loading"
        row-key="techID"
        :default-expand-all-rows="true"
        :scroll="{ x: 'auto', y: 'auto' }"
        :pagination="pagination"
        class="h-full"
        :custom-row="customRow"
        :row-height="23"
      />
      <!-- 手动同步弹窗 -->
      <Modal v-model:visible="detailsVisibleQrcode" :destroy-on-close="true" title="手动工序流程信息" width="550px">
        <div class="event-form">
          <Form v-model:model="crDatas" :form-list="formListqr"></Form>
        </div>
        <template #footer>
          <div class="modal-footer">
            <AButton @click="detailsVisibleQrcode = false">关闭</AButton>
            <AButton type="primary" @click="boundUpdata">保存</AButton>
          </div>
        </template>
      </Modal>
      <!-- 新增和修改弹窗 -->
      <Modal
        v-model:visible="modalVisible"
        :destroy-on-close="true"
        :centered="true"
        :title="formTit"
        width="500px"
        height="470px"
      >
        <Add ref="addFormRef" :row-data="currentRow" :operate-type="operateType"></Add>
        <template #footer>
          <div class="modal-footer">
            <AButton @click="modalVisible = false">关闭</AButton>
            <AButton type="primary" @click="boundUpdataAdd(formTit)">保存</AButton>
          </div>
        </template>
      </Modal>
    </ACard>
  </div>
</template>

<style></style>
